package com.xzl.shop.server;

import com.xzl.manger.model.Order;
import com.xzl.manger.model.OrderGood;
import com.xzl.manger.server.OrderServer;
import com.xzl.shop.dao.ICartDao;
import com.xzl.shop.model.Cart;
import com.xzl.shop.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CartServer {
    @Autowired
    private ICartDao cartDao;
    @Autowired
    private UserServer userServer;
    @Autowired
    private OrderServer orderServer;
    public List<Cart> selectCart(Cart cart){
        return cartDao.selectCart(cart);
    }
    public Integer addCart(Cart cart){
        return cartDao.addCart(cart);
    }
    public Integer delete(Cart cart){
        if (cart == null || cart.getId() == null) return 0;
        return cartDao.delete(cart);
    }
    public Integer submit(String ids){
        String idsz[] = ids.split(",");
        List<Cart> list = new ArrayList<>();
        BigDecimal money = BigDecimal.valueOf(0);
        for (int i = 0; i < idsz.length; i++){
            list.add(cartDao.selectCart(new Cart(idsz[i])).get(0));
            money = money.add(cartDao.selectCart(new Cart(idsz[i])).get(0).getMoney());
        }
        Cart cart = list.get(0);
        User user = new User();
        user.setId(cart.getUserId());
        user = userServer.selectUser(user).get(0);
        String phone = user.getPhone();
        Date date = new Date();
        SimpleDateFormat spf = new SimpleDateFormat("yyyyMMddHHmmss");
        String orderId = spf.format(date) + phone.substring(phone.length()-4,phone.length());
        Order order = new Order(orderId);
        order.setUserId(cart.getUserId());
        order.setOrderMoney(money);
        orderServer.insertOrder(order);
        for (Cart c : list){
            OrderGood orderGood = new OrderGood(c);
            orderGood.setOrderId(orderId);
            orderServer.insertOrderGood(orderGood);
            cartDao.delete(c);
        }
        return cart.getUserId();
    }

    public Integer deleteCarts(String ids){
        String idsz[] = ids.split(",");
        Cart c = cartDao.selectCart(new Cart(idsz[0])).get(0);
        for (String id : idsz) {
            delete(new Cart(id));
        }
        return c.getUserId();
    }
}
